/*
 * $Id: sed.c,v 1.1 2006-04-23 16:05:59 bacon Exp $
 */

#include <xp/utl/sed.c>
#include <xp/bas/memory.h>

struct xp_sed_t
{
	xp_sed_io_t io;
	void* io_arg;	
	int errnum;
};

static int __run_sed (xp_sed_t* sed, const xp_char_t* cmd);

xp_sed_t* xp_sed_open (void)
{
	xp_sed_t* sed;

	sed = (xp_sed_t*) xp_malloc (xp_sizeof(xp_sed_t));
	if (sed == XP_NULL) return XP_NULL;

	sed->io = XP_NULL;
	sed->io_arg = XP_NULL;
	sed->errnum = XP_SED_ENOERR;

	return sed;
}

void xp_sed_close (xp_sed_t* sed)
{
	xp_free (sed);
}

int xp_sed_run (xp_sed_t* sed, const xp_char_t* cmds[], xp_size_t ncmds)
{
	xp_size_t i;

	if (sed->io == XP_NULL) 
	{
		sed->errnum = XP_SED_ENOIO;
		return -1;
	}

	if (sed->io (XP_SED_INPUT_OPEN, sed->io_arg, XP_NULL, 0) == -1)
	{
		sed->errnum = XP_SED_EINOPEN;
		return -1;
	}

	if (sed->io (XP_SED_OUTPUT_OPEN, sed->io_arg, XP_NULL, 0) == -1)
	{
		sed->io (XP_SED_INPUT_CLOSE, sed->io_arg, XP_NULL, 0);
		sed->errnum = XP_SED_EOUTOPEN;
		return -1;
	}

	for (i = 0; i < ncmds; i++)
	{
		if (__run_sed (sed, cmds[i]) == -1) return -1;
	}

	if (sed->io (XP_SED_INPUT_CLOSE, sed->io_arg, XP_NULL, 0) == -1)
	{
		sed->io (XP_SED_OUTPUT_CLOSE, sed->io_arg, XP_NULL, 0);
		sed->errnum = XP_SED_EOUTCLOSE;
		return -1;
	}

	if (sed->io (XP_SED_OUTPUT_CLOSE, sed->io_arg, XP_NULL, 0) == -1)
	{
		sed->errnum = XP_SED_EOUTCLOSE;
		return -1;
	}

	return 0;
}

static int __run_sed (xp_sed_t* sed, const xp_char_t* cmd)
{
	return -1;
}
